# -*- coding:utf-8 -*-
# @FileName : app\api\v1\models\routes.py
# @Time     : 2025/11/28
# @Author   : 天空之城
"""模型API模块路由文件

此模块定义模型调用相关的API路由，处理HTTP请求和响应。
"""
from flask import Blueprint, request
from app.utils.response_factory import ResponseFactory
from flask_jwt_extended import jwt_required
from app.api.v1.models.services import ModelService
from app.api.v1.models.schemas import ModelRequestSchema, ModelResponseSchema, ModelListResponseSchema

# 创建模型API蓝图
models_bp = Blueprint('models', __name__)

# 初始化服务和模式
model_service = ModelService()
model_request_schema = ModelRequestSchema()
model_response_schema = ModelResponseSchema()
model_list_response_schema = ModelListResponseSchema()


@models_bp.route('/supported', methods=['GET'])
@jwt_required()
def get_supported_models():
    """获取支持的模型列表
    
    Returns:
        JSON格式的支持的模型列表
    """
    try:
        models = model_service.get_supported_models()
        response = {'models': models}
        return ResponseFactory.success(data=model_list_response_schema.dump(response))
    except Exception as e:
        return ResponseFactory.error(msg='获取模型列表失败', code=500, errors=str(e))


@models_bp.route('/call', methods=['POST'])
@jwt_required()
def call_model():
    """调用指定类型的模型生成响应
    
    Returns:
        JSON格式的模型响应
    """
    try:
        # 验证请求数据
        data = request.get_json()
        errors = model_request_schema.validate(data)
        if errors:
            return ResponseFactory.error(msg='请求数据验证失败', code=400, errors=errors)
        
        # 调用模型服务
        response = model_service.call_model(
            model_type=data['model_type'],
            messages=data['messages'],
            tools=data.get('tools'),
            tool_choice=data.get('tool_choice', 'auto'),
            temperature=data.get('temperature', 0.1)
        )
        
        return ResponseFactory.success(data=model_response_schema.dump(response), msg='模型调用成功')
    except ValueError as e:
        return ResponseFactory.error(msg='参数错误', code=400, errors=str(e))
    except Exception as e:
        return ResponseFactory.error(msg='模型调用失败', code=500, errors=str(e))